package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SecKillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.LoginRespEntity;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.constant.PayConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.exception.NoStockException;
import com.atguigu.gulimall.order.feign.MemberOrderFeignService;
import com.atguigu.gulimall.order.feign.OrderCartFeignService;
import com.atguigu.gulimall.order.feign.OrderProductFeignService;
import com.atguigu.gulimall.order.feign.OrderWareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.enums.EnumUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;

@SuppressWarnings("All")
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private MemberOrderFeignService memberOrderFeignService;

    @Resource
    private OrderCartFeignService orderCartFeignService;

    //自动注入我们给容器配置的线程池
    @Autowired
    ThreadPoolExecutor executor;

    @Resource
    private OrderWareFeignService orderWareFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderProductFeignService orderProductFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要用的数据
     */
    @SuppressWarnings("all")
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //首先根据拦截器获取用户信息
        LoginRespEntity user = LoginUserInterceptor.threadLocal.get();
        // 从主线程获取数据，解决异步情况下请求头数据丢失问题
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddreassFuture = CompletableFuture.runAsync(() -> {
            // 异步线程共享 RequestContextHolder.getRequestAttributes()
            RequestContextHolder.setRequestAttributes(attributes);
            //1、远程查询会员服务得到地址列表
            List<MemberAddressVo> address = memberOrderFeignService.getAddress(user.getId());
            orderConfirmVo.setAddressVoList(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 异步线程共享 RequestContextHolder.getRequestAttributes()
            RequestContextHolder.setRequestAttributes(attributes);
            //2、远程查询购物车服务得到所有选中的购物项
            List<OrderItemVo> items = orderCartFeignService.getUserCartItems();
            orderConfirmVo.setItems(items);
        }, executor)
                .thenRunAsync(() -> {  //查询完购物车中的每个购物项之后，就查询商品是否有货
                    //拿到上一步查询返回的数据
                    List<OrderItemVo> items = orderConfirmVo.getItems();
                    //批量查询每个商品的库存信息,首先收集到每一项的id
                    List<Long> skuIds = items.stream().map(item -> {
                        return item.getSkuId();
                    }).collect(Collectors.toList());
                    R skuHasStock = orderWareFeignService.getSkuHasStock(skuIds);
                    //得到每个库存的状态信息
                    List<SkuStockVo> data = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {
                    });
                    //将信息加工成map放入orderConfirmVo，因为页面的效果是订单确认页有多个商品需要计算是否有库存，
                    if (data != null) {
                        //map中key就表示了哪个商品，就是商品的id，value表示这个商品是否有库存
                        Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(
//                                SkuStockVo::getSkuId, SkuStockVo::getHasStock
                                k -> k.getSkuId(), v -> v.getHasStock()
                        ));
                        orderConfirmVo.setStocks(map);
                    }
                }, executor);


        //3、查询用户积分信息
        Integer integration = user.getIntegration();
        orderConfirmVo.setIntegration(integration);
        //4、其他数据自动计算
        //TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //接下来要将token给页面一个，然后给服务器一个，最后将两者对比,redis中的过期时间是30分钟
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + user.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        //等待所有异步任务全部完成
        CompletableFuture.allOf(getAddreassFuture, cartFuture).get();
        return orderConfirmVo;
    }

    /**
     * 提交订单的方法
     */
    @SuppressWarnings("all")
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo submitVo) {
        //共享OrderSubmitVo，主要是里面的地址信息
        orderSubmitVoThreadLocal.set(submitVo);
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();//返回的数据
        submitOrderResponseVo.setCode(0);//如果有任何异常，返回的就不是0
        LoginRespEntity loginRespEntity = LoginUserInterceptor.threadLocal.get();//获取用户信息
        // 0 令牌删除失败 1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        //1、验证令牌[令牌的对比和删除必须是原子操作] 返回 0 or 1
        String indexToken = submitVo.getOrderToken();//这是页面提交的令牌
        //redis执行lua脚本,原子验证令牌和删除令牌,DefaultRedisScript中的泛型表示的是脚本的返回类型
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>
                        (script,
                                Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginRespEntity.getId()),
                indexToken);
        if (result == 0L) {
            //验证失败
            submitOrderResponseVo.setCode(1);//返回给Controller一个状态码表示验证失败
            return submitOrderResponseVo;
        } else {
            //验证成功
            //1、首先创建订单，生成订单号
            OrderCreateTo order = createOrderTo();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();//这是订单自己算的金额
            BigDecimal payPrice = submitVo.getPayPrice();//页面提交过来的金额
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                /****************/
                //对比成功,将订单中所有数据保存到数据库
                //TODO 3、保存订单
                saveOrder(order);
                //4、库存锁定 库存锁定失败还要撤销订单,只要有异常就回滚订单数据
                //调用远程库存服务，需要的参数有订单号，所有的订单项（skuId，skuName，num数量）
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                //TODO 4、远程锁定库存
                //为了保证高并发，库存服务自己回滚，可以发消息给库存服务
                //库存服务也可以使用自动解锁模式
                R r = orderWareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    submitOrderResponseVo.setOrder(order.getOrder());
                    //TODO 5、远程扣减积分 失败
//                    int i = 10 / 0;//订单回滚，库存不滚
                    //TODO 订单创建成功，发送消息给MQ
                    //发送消息到订单延迟队列，判断过期订单
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return submitOrderResponseVo;
                } else {
                    //锁定失败,都要回滚，订单也不能添加到数据库，因此可以使用抛异常的方式让它回滚
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                    // submitOrderResponseVo.setCode(3);
                    // return submitOrderResponseVo;
                }
            } else {
                //验价失败
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }
        }
        //从redis中查出服务器的令牌
//        String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginRespEntity.getId());
//        if (indexToken != null && redisToken != null && indexToken.equals(redisToken)) {
//            //令牌验证通过
//        } else {
//            //验证不通过
//        }
//        return submitOrderResponseVo;
    }

    /**
     * 根据订单号查询订单状态，现在是直接返回一个实体类
     */
    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询最新状态
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity, orderTo);
            //发送消息给库存
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    /**
     * 根据订单号获取支付信息
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        //根据订单号得到订单实体
        OrderEntity orderEntity = this.getOrderStatus(orderSn);
        //根据订单号查询订单项实体
        List<OrderItemEntity> itemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().
                eq(OrderItemEntity::getOrderSn, orderSn));
        // 商户订单号 必填
        payVo.setOut_trade_no(orderEntity.getOrderSn());
        // 订单名称 必填
        OrderItemEntity orderItemEntity = itemEntities.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        // 付款金额 必填
        //支付金额设置为两位小数，否则会报错,而数据库中是4位小数，所以需要转化
        //setScale:https://blog.csdn.net/ahwr24/article/details/7048724
        BigDecimal payAmount = orderEntity.getPayAmount().
                setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        // 商品描述 可空
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 分页查询某个会员的所有订单
     *
     * @Override public PageUtils queryPage(Map<String, Object> params) {
     * IPage<OrderEntity> page = this.page(
     * new Query<OrderEntity>().getPage(params),
     * new QueryWrapper<OrderEntity>()
     * );
     * return new PageUtils(page);
     * }
     */
    @Override
    public PageUtils listWithItem(Map<String, Object> params) {

        LoginRespEntity memberResponseVo = LoginUserInterceptor.threadLocal.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", memberResponseVo.getId()).orderByDesc("create_time")
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);

//        //得到用户信息
//        LoginRespEntity loginRespEntity = LoginUserInterceptor.threadLocal.get();
//        //得到所有的翻页数据
//        IPage<OrderEntity> page = this.page(
//                new Query<OrderEntity>().getPage(params),
//                new LambdaQueryWrapper<OrderEntity>().
//                        eq(OrderEntity::getMemberId, loginRespEntity.getId()).
//                        orderByDesc(OrderEntity::getCreateTime)
//        );
//        //得到所有的记录.也就是遍历所有的订单
//        List<OrderEntity> records = page.getRecords();
//        //对于每个订单，遍历得到它的所有订单项，根据订单号
//        List<OrderEntity> collect = records.stream().map(orderEntity -> {
//            List<OrderItemEntity> orderItemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().
//                    eq(OrderItemEntity::getOrderSn, orderEntity.getOrderSn()));
//            orderEntity.setItemEntities(orderItemEntities);
//            return orderEntity;
//        }).collect(Collectors.toList());
//        page.setRecords(collect);
//        return new PageUtils(page);
    }


    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 处理支付宝的支付结果
     */
    @SuppressWarnings("all")
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
//保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SecKillOrderTo orderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
        R spuInfo = orderProductFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandId().toString());
        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }

    /**
     * 修改订单状态
     *
     * @param orderSn
     * @param code
     */
    private void updateOrderStatus(String orderSn, Integer code) {
        this.baseMapper.updateOrderStatus(orderSn, code);
    }

    @Autowired
    private OrderItemService orderItemService;

    //保存订单到数据库
    @SuppressWarnings("all")
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        //修改新增时间可以使用mybatisplus中的注解直接补充，此处为了方便直接set
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.baseMapper.insert(orderEntity);//保存订单
        //因为有很多的订单项，所以可以使用批量保存
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItems = orderItems.stream().map(item -> {
            //设置还未在构建一个订单项中未设置的数据
            item.setOrderId(orderEntity.getId());
            item.setSpuName(item.getSpuName());
            item.setOrderSn(order.getOrder().getOrderSn());
            return item;
        }).collect(Collectors.toList());
        orderItemService.saveBatch(orderItems);//批量保存
    }

    /**
     * 创建订单的方法
     */
    private OrderCreateTo createOrderTo() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //根据订单号构建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //获得所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //计算价格相关  需要传入订单和订单项
        computerPrice(orderEntity, orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    //计算价格相关
    @SuppressWarnings("all")
    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 叠加每一个订单项的金额
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        BigDecimal totalPrice = new BigDecimal(0.0);
        for (OrderItemEntity orderItemEntity : orderItemEntities) {//遍历所有得订单项价格
            BigDecimal realAmount = orderItemEntity.getRealAmount();//当前订单项得实际金额，已经在构建一个订单项中设置过
            //而订单得总额就是这些实际价格得叠加
            totalPrice = totalPrice.add(realAmount);
            // 优惠券的金额
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            // 积分优惠的金额
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            // 打折的金额
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            // 购物获取的积分、成长值
            gift.add(new BigDecimal(orderItemEntity.getGiftIntegration().toString()));
            growth.add(new BigDecimal(orderItemEntity.getGiftGrowth().toString()));
        }
        // 1.订单价格相关 总额、应付总额
        orderEntity.setTotalAmount(totalPrice);
        //应付金额应该是订单的真实金额加上运费的价格
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
//        orderEntity.setFreightAmount();这是运费价格已经在构建订单的时候set过了，这里也就不需要了
        // 设置积分、成长值，每个订单项的积分和成长值已经在构建一个订单项中设置好
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());

        // 设置订单的删除状态  0表示未删除，1表示已删除，
        orderEntity.setDeleteStatus(OrderStatusEnum.CREATE_NEW.getCode());//待付款状态
    }


    //构建订单
    @SuppressWarnings("all")
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        //会员信息可以直接从拦截器中拿到，因为整个业务都是一个线程的
        LoginRespEntity loginRespEntity = LoginUserInterceptor.threadLocal.get();
        //1) 设置用户信息
        orderEntity.setMemberId(loginRespEntity.getId());
        orderEntity.setMemberUsername(loginRespEntity.getUsername());

        orderEntity.setOrderSn(orderSn);
        //下面还会有方法用到OrderSubmitVo中的地址信息，因此这样传递不方便，而这又是一个线程完成的，所以还是使用ThreadLocal进行共享
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        //根据地址id远程查询运费
        R fare = orderWareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        orderEntity.setFreightAmount(fareVo.getFare());//设置运费信息
        MemberAddressVo address = fareVo.getMemberAddressVo();
        //将地址信息设置到订单实体类中
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        // 设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);//自动确认收获时间
        return orderEntity;
    }

    //构建所有的订单项,参数表示为哪个订单构建订单项
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //远程查询购物车得到所有的订单项
        List<OrderItemVo> userCartItems = orderCartFeignService.getUserCartItems();
        List<OrderItemEntity> orderItemEntities = null;
        //判断其中有数据
        if (userCartItems != null && userCartItems.size() > 0) {
            orderItemEntities = userCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntities;
    }


    @SuppressWarnings("all")
    //构建一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1.订单信息： 订单号,表示这个订单项是属于哪个订单的，上述已经做过了
        // 2.商品spu信息
        Long skuId = cartItem.getSkuId();//现在只知道skuId，所以要查
        R spuInfoBySkuId = orderProductFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfo = spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfo.getId());
        orderItemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfo.getSpuName());
        orderItemEntity.setCategoryId(spuInfo.getCatalogId());
        // 3.商品的sku信息,就在我们传入的OrderItemVo中
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //这里要求的是String，而OrderItemVo中是一个List集合，可以转换一下
        // 属性list生成一个string  https://www.cxyzjd.com/article/lliuhongyang/77879158
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        // 4.积分信息 买的数量越多积分越多 成长值越多
        orderItemEntity.setGiftGrowth(
                cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(
                cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        // 5.订单项的价格信息 优惠金额
        // 5.订单项的价格信息 优惠金额
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        // 当前订单项的实际金额
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        // 减去各种优惠的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()).
                subtract(orderItemEntity.getPromotionAmount()).
                subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }


}